package com.asm.handler;

import com.asm.message.RpcResponseMessage;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.concurrent.Promise;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
@ChannelHandler.Sharable
public class RpcResponseMessageHandler extends SimpleChannelInboundHandler<RpcResponseMessage> {
    /**
     * @param Integer 序号
     * @param  Promise 用来接收结果的对象
     *选择ConcurrentHashMap是因为将来多个线程都要放,还需要保证线程安全性
     * */
    public static final Map<Integer,Promise<Object>> PROMISE=new ConcurrentHashMap<>();
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, RpcResponseMessage msg) throws Exception {
      //拿到空的promise  泛型通配符只能取不能放  remove返回对应的值，然后从集合中删除
        Promise<Object> promise = PROMISE.remove(msg.getSequenceId());
       //判断promise是否为空
        if (promise!=null) {
            //正常结果
            Object returnValue = msg.getReturnValue();
            //异常结果
            Exception exceptionValue = msg.getExceptionValue();
            //如果exceptionValue不是null，证明有异常信息
          if(exceptionValue!=null){
              promise.setFailure(exceptionValue);
          }else{
              promise.setSuccess(returnValue);
          }


        }





        log.debug("{}",msg);
    }
}
